define(['vue','common',"WangEditor",'jquery','ELEMENT'],function (Vue,common,WangEditor,$,ELEMENT){
    const { ElMessage} = ELEMENT;
    const muform = {
        template:`<el-scrollbar style="height: calc(100vh - 100px)">
        <el-form ref="form" :model="options"  :label-width="options.labelWidth?options.labelWidth:'100px'">
            <template v-for="(item,index) in options.form">
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="!item.type||item.type=='input'||item.type=='text'">
                   <el-input v-model="options.form[index].value" :style="{width: item.width?item.width:'240px'}" :placeholder="item.placeholder?item.placeholder:'请输入'+item.label" ></el-input>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='textarea'">
                   <el-input v-model="options.form[index].value" type="textarea" :style="{width: item.width?item.width:'240px'}" :rows="item.rows?item.rows:5" :placeholder="item.placeholder?item.placeholder:'请输入'+item.label" ></el-input>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='img'">
                   <MuAvatarUpload v-model="options.form[index].value" :hasXz="true"></MuAvatarUpload>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='imgs'">
                   <MuAvatarUploads v-model="options.form[index].value" :hasXz="true"></MuAvatarUploads>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='file'">
                   <MuFileUpload v-model="options.form[index].value"></MuFileUpload>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='select'">
                       <el-select
                          v-model="options.form[index].value"
                          :placeholder="item.placeholder?item.placeholder:'请选择'+item.label"
                          size="large"
                          clearable
                          style="width: 240px"
                        >
                        <template v-if="Array.isArray(item.options)">
                        <el-option
                            v-for="(items,keys) in item.options"
                            :key="items.value"
                            :label="items.label"
                            :value="items.value"
                          >
                          </el-option>
                        </template>
                        <template v-else>
                            <el-option
                                v-for="(items,keys) in item.options"
                                :key="keys"
                                :label="items"
                                :value="keys"
                              >
                              </el-option>
                        </template>
                          
                        </el-select>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='selects'">
                       <el-select
                          v-model="options.form[index].value"
                          :placeholder="item.placeholder?item.placeholder:'请选择'+item.label"
                          size="large"
                          clearable
                          multiple
                          style="width: 240px"
                        >
                        <template v-if="Array.isArray(item.options)">
                        <el-option
                            v-for="(items,keys) in item.options"
                            :key="item.valueField?items[item.valueField]:items.value"
                            :label="item.labelField?items[item.labelField]:items.label"
                            :value="item.valueField?items[item.valueField]:items.value"
                          >
                          </el-option>
                        </template>
                        <template v-else>
                            <el-option
                                v-for="(items,keys) in item.options"
                                :key="keys"
                                :label="items"
                                :value="keys"
                              >
                              </el-option>
                        </template>
                          
                        </el-select>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='switch'">
                    <template v-if="item.value&&(typeof item.value)=='string'">
                        <el-switch v-model="options.form[index].value" active-value="1" inactive-value="0" :active-text="item.option?item.option['1']:'开启'" :inactive-text="item.option?item.option['0']:'关闭'"></el-switch>
                    </template>
                    <template v-else-if="item.value&&(typeof item.value)=='number'">
                        <el-switch v-model="options.form[index].value" :active-value="1" :inactive-value="0" :active-text="item.option?item.option[1]:'开启'" :inactive-text="item.option?item.option[0]:'关闭'"></el-switch>
                    </template>
                    <template v-else>
                        <el-switch v-model="options.form[index].value" :active-value="1" :inactive-value="0" :active-text="item.option?item.option[1]:'开启'" :inactive-text="item.option?item.option[0]:'关闭'"></el-switch>
                    </template>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='cascader'">
                    <el-cascader
                            v-if="item.multiple==true"
                          v-model="options.form[index].value"
                          :options="item.options"
                          :props="{checkStrictly:true,multiple:true}"
                        >
                        </el-cascader>
                        <el-cascader
                            v-else
                          v-model="options.form[index].value"
                          :options="item.options"
                          :props="{checkStrictly:true}"
                        >
                        </el-cascader>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='radio'">
                    <el-radio-group v-model="options.form[index].value">
                        <template v-for="(items,keys) in item.options">
                            <el-radio v-if="Array.isArray(item.options)" :value="item.valueField?items[item.valueField]:items.value">{{item.labelField?items[item.labelField]:items.label}}</el-radio>
                            <el-radio v-else :value="keys">{{items}}</el-radio>
                        </template>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='checkbox'">
                    <el-checkbox-group v-model="options.form[index].value">
                        <template v-for="(items,keys) in item.options">
                            <el-checkbox v-if="Array.isArray(item.options)" :label="item.labelField?items[item.labelField]:items.label" :value="item.valueField?items[item.valueField]:items.value"></el-checkbox>
                            <el-checkbox v-else :label="item.labelField?items[item.labelField]:items.label" :value="keys"></el-checkbox>
                        </template>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='array'">
                    <KeyValue v-model="options.form[index].value"></KeyValue>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='date'">
                     <el-date-picker
                        style="width: 240px"
                        v-model="options.form[index].value"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期"
                      ></el-date-picker>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='daterange'">
                <div style="width: 240px">
                    <el-date-picker
                            v-model="options.form[index].value"
                            type="daterange"
                            value-format="YYYY-MM-DD"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                    >  
                    </el-date-picker>
                </div>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='datetime'">
                     <el-date-picker
                        style="width: 240px"
                        v-model="options.form[index].value"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择日期时间"
                      ></el-date-picker>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='datetimerange'">
                    <div style="width: 240px">
                        <el-date-picker
                                v-model="options.form[index].value"
                                type="datetimerange"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                        >  
                        </el-date-picker>
                    </div>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='time'">
                    <el-time-picker
                      v-model="options.form[index].value"
                      value-format="HH:mm:ss"
                      placeholder="请选择时间"
                    ></el-time-picker>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='timerange'">
                <div style="width: 240px">
                    <el-time-picker
                          v-model="options.form[index].value"
                          is-range
                          value-format="HH:mm:ss"
                          range-separator="至"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                        ></el-time-picker>
                </div>
                    
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='range'">
                    <div class="flex-row flex-content-center">
                        <el-input v-model="options.form[index].value[0]" style="margin-right: 5px" placeholder="最小"></el-input>
                        -
                        <el-input style="margin-left: 5px" v-model="options.form[index].value[1]" placeholder="最大"></el-input>
                    </div>
                </el-form-item>
                <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='color'">
                    <el-color-picker v-model="options.form[index].value"></el-color-picker>
                </el-form-item>
                 <el-form-item :label="item.label" :prop="'form.'+index+'.value'" :rules="item.rules" v-if="item.type=='editor'">
                   <div class="flex-column" style="width: 600px;height: 600px;border:1px solid #dddddd">
                        <div :ref="item.name+'_toolbar'"></div>
                        <div :ref="item.name+'_editor'" style="height: 600px;overflow-y: auto;"></div>
                    </div>
                </el-form-item>
            </template>
        </el-form>
    </el-scrollbar>
    <div style="display: flex;justify-content: flex-end;margin-top: 20px" class="flex-column flex-item-center">
        <div >
            <el-button v-if="isEdit==false" type="primary" @click="onSubmitAdd">立即创建</el-button>
            <el-button v-else type="primary" @click="onSubmitAdd">保存修改</el-button>
            <el-button @click="onCancel">取消</el-button>
        </div>
    </div>`,
        data(){
            return {
                rules:{

                },
                arrValueTypeList:[
                    'imgs',
                    'files',
                    'selects',
                    'cascader',
                    'checkbox',
                    'array',
                    'daterange',
                    'datetimerange',
                    'timerange',
                    'range'
                ],
                hasTwoTypeList:[
                    'daterange',
                    'datetimerange',
                    'timerange',
                    'range'
                ]
            }
        },
        props:{
            options:{
                type:Object,
                default:function(){
                    return {}
                }
            },
            isEdit:{
                type:Boolean,
                default:false
            },
            url:{
                type:String,
                default:''
            }
        },
        created(){
            console.log(this.isEdit,'isEdit')
            let form = this.options?.form?this.options.form:[]
            let rules = {}
            let that = this
            form.forEach(item=>{
                let temrules = [];
                if(item.required){
                    temrules.push({
                        required:true,
                        message:item.label+'不能为空',
                        trigger:'blur'
                    })
                }
                if(item.rules){
                    temrules.push(...item.rules)
                }
                if(that.arrValueTypeList.includes(item.type)){
                    if(that.hasTwoTypeList.includes(item.type)){
                        if(!item.value||!item.value[0]){
                            item.value = ['','']
                        }

                    }else{
                        if(!item.value||!item.value.length==0){
                            item.value = []
                        }
                    }

                }else{
                    if(!item.value){
                        item.value = ''
                    }

                }
                item.rules = temrules
                // that.formData.push(item)
            })
            this.options.form = form
            // console.log(rules,'------------------')
            // this.rules =  rules
        },
        mounted(){
            const {createEditor, createToolbar} = WangEditor
            // console.log(9999)
            let editors = this.options?.form.filter(item=>item.type=='editor')
            let that = this;
            const editorConfig = {
                height: 460, // 800px总高度 - 60px工具栏
                placeholder: '请输入内容...',
                scroll: true,
                MENU_CONF:{
                    uploadImage:{
                        server:`/app/muadmin/admin/ajax/upload`,
                        fieldName:"file",
                        maxNumberOfFiles: 1,
                        allowedFileTypes: ['image/*'],
                        timeout: 30 * 1000,
                        onSuccess(file, res) {
                            console.log('上传成功', file, res)
                        },
                        // 上传失败回调
                        onFailed(file, res) {
                            console.error('上传失败', file, res)
                            alert(`上传失败: ${res.message || '未知错误'}`)
                        },

                        // 上传错误回调
                        onError(file, err, res) {
                            console.error('上传错误', file, err, res)
                            alert(`上传错误: ${err.message || '未知错误'}`)
                        },
                        customInsert(res, insertFn){
                            insertFn(res.data.url)
                        }
                    },
                    uploadVideo: {
                        server:`/app/muadmin/admin/ajax/upload`,
                        fieldName:"file",
                        maxNumberOfFiles: 1,
                        allowedFileTypes: ['video/*'],
                        timeout: 30 * 1000,
                        onSuccess(file, res) {
                            console.log('上传成功', file, res)
                        },
                        // 上传失败回调
                        onFailed(file, res) {
                            console.error('上传失败', file, res)
                            alert(`上传失败: ${res.message || '未知错误'}`)
                        },

                        // 上传错误回调
                        onError(file, err, res) {
                            console.error('上传错误', file, err, res)
                            alert(`上传错误: ${err.message || '未知错误'}`)
                        },
                        customInsert(res, insertFn){
                            insertFn(res.data.url)
                        }
                    }
                }
            }; // 这里可以配置编辑器的选项，如 placeholder 等
            const toolbarConfig = {

            }; // 这里可以配置工具栏的选项
            function debounce(fn, delay) {
                let timer = null
                return function() {
                    if (timer) clearTimeout(timer)
                    timer = setTimeout(() => fn.apply(this, arguments), delay)
                }
            }
            for (let item of editors){
                let editor = createEditor({
                    selector: that.$refs[`${item.name}_editor`],
                    config: editorConfig,
                    html:item.value,
                    mode: 'simple'
                    // mode: 'default'
                })
                editor.on('change', debounce(function (){
                    let index = that.options.form.findIndex(items=>items.name==item.name)
                    that.options.form[index].value = editor.getHtml()
                },500))
                let toolbar = createToolbar({
                    selector: that.$refs[`${item.name}_toolbar`],
                    config: toolbarConfig,
                    editor
                })
            }

            // const editorConfig = {
            //     placeholder: '请输入内容',
            //     MENU_CONF: {
            //         uploadImg: {
            //             maxSize: 1024 * 1024 * 2,
            //             maxLength: 5,
            //             server: '/api/upload/file',
            //             fieldName: 'file'
            //         }
            //     }
            // }

            // console.log(editors,'refsrefsrefsrefsrefsrefsrefsrefsrefsrefsrefsrefsrefsrefsrefs')
            // console.log(this.rules,'rulesrulesrulesrules')
        },
        methods:{
            onCancel(){
                let index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            },
            getForm(){
                let form = this.options.form;
                let data = {}
                let that = this
                form.forEach(item=>{
                    if(that.arrValueTypeList.includes(item.type)){
                        if(that.hasTwoTypeList.includes(item.type)){
                            if(item.value[0]!=''||item.value[1]!=''){
                                data[item.name] = item.value
                            }
                        }else{
                            if(item.value.length>0){
                                data[item.name] = item.value
                            }
                        }
                    }else{
                        if(item.value!==''&&item.value!==null){
                            data[item.name] = item.value
                        }
                    }
                })
                return data
            },
            onSubmitAdd(){
                let url = this.url?this.url:Config.sub_url
                let data = {
                    row:this.getForm()
                }
                console.log(data,this.rules)
                let that = this
                this.$refs.form.validate(valid=>{
                    // console.log(valid)
                    if(valid){
                        $.post(url,data,function (res){
                            if(res.code==1){
                                ElMessage({
                                    message: res.msg,
                                    type: 'success',
                                    onClose:function () {
                                        that.onCancel()
                                    }
                                })
                            }else{
                                ElMessage({
                                    message: res.msg?res.msg:'操作失败',
                                    type: 'error',
                                })
                            }
                        })
                    }
                })

                // console.log(data)
            }
        }
    }
    return muform
})